const fs = require('fs')
const path = require('path')
const child_process = require('child_process');

function fsCopy(from, to) {
    const fromPath = path.resolve(from)
    const toPath = path.resolve(to)
    fs.access(toPath, function(err) {
        if (err) {
            fs.mkdirSync(toPath)
        }
    })
    fs.readdir(fromPath, function(err, paths) {
        if (err) {
            console.log('fCopy err:',err)
            return
        }
        paths.forEach(function(item) {
            const newFromPath = fromPath + '/' + item
            const newToPath = path.resolve(toPath + '/' + item)

            fs.stat(newFromPath, function(err, stat) {
                if (err) return
                if (stat.isFile()) {
                    console.log('isFile:',newToPath)
                    copyFile(newFromPath, newToPath)
                }
                if (stat.isDirectory()) {
                    console.log('isDirectory:',newFromPath)
                    copy(newFromPath, newToPath)
                }
            })
        })
    })
}

function copyFile(from, to) {
    fs.copyFileSync(from, to, function(err) {
        if (err) {
            return
        }
    })
}

 
function linuxCopy(from, to) {
    child_process.spawn('cp', ['-r', from, to]);    
}

module.exports = {
    linuxCopy,
    fsCopy
}